package com.liaoban.app.converter;

import com.google.gson.TypeAdapter;
import com.liaoban.app.api.type.comment.BaseResponse;
import com.liaoban.app.exception.AppException;

import java.io.IOException;

import okhttp3.ResponseBody;
import retrofit2.Converter;

final class GsonResponseBodyConverter<T> implements Converter<ResponseBody, T> {
    private final TypeAdapter<T> adapter;

    GsonResponseBodyConverter(TypeAdapter<T> adapter) {
        this.adapter = adapter;
    }

    @Override
    public T convert(ResponseBody value) throws IOException {
        try {
            String json = value.string();
            T t = adapter.fromJson(json);
            if (t instanceof BaseResponse) {
                BaseResponse baseResponse = (BaseResponse) t;
                if (baseResponse.status != 200) {
                    throw AppException.createCustomAppException(baseResponse.status, baseResponse.msg);
                }
            }
            return t;
        } finally {
            value.close();
        }
    }
}
